package com.jm3.riscar3.helpers;

import com.jm3.riscar3.exceptions.BitStringException;
import com.jm3.riscar3.exceptions.NotARegisterException;
import com.jm3.riscar3.exceptions.OutOfBoundsMemoryLocationException;

public class BinaryTranslator {

	public static int getRegister(String regStr) throws NotARegisterException 
	{	
		if(regStr.equals("000"))
			return 0;
		else if(regStr.equals("001"))
			return 1;
		else if(regStr.equals("010"))
			return 2;
		else if(regStr.equals("011"))
			return 3;
		else if(regStr.equals("100"))
			return 4;
		else if(regStr.equals("101"))
			return 5;
		else if(regStr.equals("110"))
			return 6;
		else if(regStr.equals("111"))
			return 7;
		else
			throw new NotARegisterException(regStr+" is not a valid Register");		
	}
	
	public static int getMemoryLocation(String memStr) throws OutOfBoundsMemoryLocationException
	{
		if(memStr.equals("00000000"))
			return 0;
		
		else
			throw new OutOfBoundsMemoryLocationException("Memory Location " + memStr + " does not exist");
	}
	
	public static int getBitValue(String binaryStr) throws BitStringException
	{
		int length = binaryStr.length();
		int result = 0;
		
		for(int i = 1; i <= length; i++)
		{
			if(binaryStr.charAt(i-1) == '1')
				result += Math.pow(2, length - i);
			else if(binaryStr.charAt(i-1) == '0')
				result += 0;
			else
				throw new BitStringException("Entered a wrong input!");
		}
		
		return result;

	}
	public static String getBitStringFromInt(int numba, int resolution){
		String returnStr="";
		for(int i=resolution-1;i>=0;i--)
			if(numba>=Math.pow(2, i)){
				returnStr+="1";
				numba=numba-(int)Math.pow(2, i);
			}
			else
				returnStr+="0";
		return returnStr;
	}
}
